#encoding=utf-8
import xadmin,ujson,time,datetime,traceback
#新页面不是model对应生成的，菜单url配置中的地址对应register_view的
from xadmin.views import BaseAdminPlugin, ModelFormAdminView, ModelAdminView, CommAdminView, csrf_protect_m
from xadmin.util import unquote
from django.utils.html import escape
from django import forms
from xadmin.layout import Fieldset, Main, Side, Row, FormHelper
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from django.utils.decorators import method_decorator
from django.http import HttpResponseRedirect
from django.views.decorators.debug import sensitive_post_parameters
from django.conf.urls import patterns, include, url
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.db.models import Count, Max, F, Q,Min,Sum
import websys.webconfig as webconfig
import websys.fun as fun
from django.db import transaction
from websys.models import (
    ServerInfo,NewInfo,LoginNews,Black_White
)
import requests,json
from  websys import (
    db_redis
)
from websys.api import InterfaceFun,cbyx_InterfaceFun
from gm_site import settings
class TestForm(forms.Form):
    """
    A form used to change the password of a user in the admin interface.
    """
    # error_messages = {
    #     'password_mismatch': _("The two password fields didn't match."),
    # }
    # password1 = forms.CharField(label=_("Password"),
    #                             widget=forms.PasswordInput)
    # password2 = forms.CharField(label=_("Password (again)"),
    #                             widget=forms.PasswordInput)

    def __init__(self,  *args, **kwargs):
        #self.user = user
        super(TestForm, self).__init__(*args, **kwargs)

#缓存平台列表
global PFINFO_LIST
PFINFO_LIST=[]#[{'pf_id':'nhmj123','name':'','games':'1,2,3'},...]
def getPlatformInfo_list():
    global PFINFO_LIST
    if not PFINFO_LIST:
        PFINFO_LIST=ServerInfo.objects.all().values('pf',"name")
getPlatformInfo_list()


#缓存平台列表
global PFINFO_LIST2
PFINFO_LIST2=[]#[{'pf_id':'nhmj123','name':'','games':'1,2,3'},...]
def getPlatformInfo_list2():
    global PFINFO_LIST2
    if not PFINFO_LIST2:
        PFINFO_LIST2=ServerInfo.objects.filter(status=0).values('pf',"name")
getPlatformInfo_list2()
#url对应的标题
URL2TITLE={'news':'公告','email':'邮件','login_news':'登录公告','white':'白名单','black':'黑名单','server':'服务器管理'}
#自定义的页面
URL2DEFINE=['email','news','login_news','white','black','server']

#金钻消耗统计页面
class CBYXSystemView(ModelAdminView):
    model = ServerInfo
    this_form = TestForm
    common_obj={'jstype':'vendor','css_js':('xadmin.form.css','datepicker.css','xadmin.plugins.css', 'xadmin.page.form.js','xadmin.widget.datetime.js')}

    html_obj={}
    for ii in URL2TITLE:
        html_obj[ii]={'title':URL2TITLE[ii]}
        html_obj[ii].update(common_obj)
    #html_obj['share'].update(common_obj)
   # html_obj['table'].update(common_obj)

    # def __init__(self,request):
    #     _title,_tmpurl='金钻消耗统计','diamondreport.html'
    #     self.title=_title
    #     self.tempurl=_tmpurl
    #     print(_title,_tmpurl)

    @csrf_protect_m
    def get(self, request,_type):
        # if not self.has_change_permission(request):
        #     raise 123#PermissionDenied
        self.obj = {}
        self.form = self.this_form()
        #print _type,'--CommonSystemView-'
        self.htmlconfig=self.html_obj[_type]
        _title,_tmpurl=self.htmlconfig['title'],'cbyx_systemdata/blank.html'
        #if 'isDefine' in self.htmlconfig and self.htmlconfig['isDefine']==1:
        if _type in URL2DEFINE:
            _tmpurl='cbyx_systemdata/%s.html'%(_type)
        self.title=_title

        self.tempurl=_tmpurl
        global PFINFO_LIST
        global PFINFO_LIST2
        #print '================',_type,type(_type)
        if str(_type) =='server':
            lists=ServerInfo.objects.filter(status=0).values('pf',"name")
            self.htmldata = {'type': _type, 'apps': lists}
        else:
            self.htmldata={'type':_type,'apps':PFINFO_LIST}

        return self.get_response()

    def get_media(self):
        media = super(CBYXSystemView, self).get_media()
        if self.htmlconfig['jstype']=='static':
            for ii in self.htmlconfig['css_js']:
                file_type = ii.split('.')[-1]
                if file_type=='css':
                    media.add_css({'screen': [ii]})
                elif file_type=='js':
                    media.add_js((self.static(ii),))
            #tmp_media=self.static(*self.htmlconfig['css_js'])
        else:
            media+=self.vendor(*self.htmlconfig['css_js'])
        media = media+ self.form.media
        return media

    def get_context(self):
        #获取数据
        context = super(CBYXSystemView, self).get_context()
        #print(context,'-------------------*****get_context*****',)
        helper = FormHelper()
        helper.form_tag = False
        self.form.helper = helper
        context.update({
            #'title': _('Change password: %s') % escape(unicode(self.obj)),
            'form': self.form,
            'has_delete_permission': False,
            'has_change_permission': True,
            'has_view_permission': True,
            'original': self.obj,
            #chong add
            'title':self.title,#_('My Information'),
            'account_view':True,
            'serverval':"服务器上的值",
            'htmldata':self.htmldata
        })
        return context

    #可以按不同的参数加载对应的页面
    def get_response(self):
        #print(self.get_context(),"----******get_response*******",self.admin_site.name)
        return TemplateResponse(self.request, [self.tempurl] , self.get_context(), current_app=self.admin_site.name)
        #return TemplateResponse(self.request, [ self.change_user_password_template or'xadmin/auth/user/change_password.html']
                               # , self.get_context(), current_app=self.admin_site.name)

class DiamondReportView(CBYXSystemView):
    def __init__(self):
        super(DiamondReportView,self)#.__init__('金钻消耗统计','diamondreport.html')

class OnlineReportView(CBYXSystemView):
    def __init__(self):
        super(OnlineReportView,self)#.__init__('在线统计','onlinereport.html')




#渲染注册请求页面,url配置
# xadmin.site.register_view(r'^core/$', CommonSystemView,name='core_report')#核心数据
# xadmin.site.register_view(r'^recharge/$', CommonSystemView,name='recharge_report')
# xadmin.site.register_view(r'^online/$', CommonSystemView,name='online_report')
# xadmin.site.register_view(r'^props/$', CommonSystemView,name='props_report')
# xadmin.site.register_view(r'^newloss/$', CommonSystemView,name='newloss_report')
# xadmin.site.register_view(r'^loadloss/$', CommonSystemView,name='loadloss_report')
xadmin.site.register_view(r'^cbyx_systemdata/(.+)/$', CBYXSystemView,name='cbyx_system_%s')#各种按日，月，年汇总页面
#ajax请求页面
urlpatterns = patterns('',
                    #充值报表
                     url(r'^addnews', 'websys.view.cbyx_systemdata.op_addnews', name='op_addnews'),
                     url(r'^getnews', 'websys.view.cbyx_systemdata.op_getnews', name='op_getnews'),
                    url(r'^change_effect', 'websys.view.cbyx_systemdata.op_change_effect', name='op_change_effect'),
                    url(r'^get_server', 'websys.view.cbyx_systemdata.op_get_server', name='op_quserver'),
                    url(r'^ch_server', 'websys.view.cbyx_systemdata.op_chserver', name='op_chserver'),
                    url(r'^sp_server', 'websys.view.cbyx_systemdata.op_spserver', name='op_spserver'),
                    url(r'^login_news', 'websys.view.cbyx_systemdata.op_login_news', name='op_login_news'),
                    url(r'^loginnew_quset', 'websys.view.cbyx_systemdata.op_loginnew_quset', name='op_loginnew_quset'),
                    url(r'^black', 'websys.view.cbyx_systemdata.op_black', name='op_black'),
                    url(r'^bw_quset', 'websys.view.cbyx_systemdata.op_bw_quset', name='op_bw_quset'),
                    url(r'^bw_delete', 'websys.view.cbyx_systemdata.op_bw_delete', name='op_bw_delete'),
                    url(r'^white', 'websys.view.cbyx_systemdata.op_white', name='op_white'),
                    url(r'^wh_quset', 'websys.view.cbyx_systemdata.op_wh_quset', name='op_wh_quset'),
                    url(r'^wh_delete', 'websys.view.cbyx_systemdata.op_wh_delete', name='op_wh_delete'),


    )

#发公告{"title":t_title, "con":t_con,"order":t_order,"pf":t_pf,"date":t0+","+t1}
@csrf_exempt
@login_required(login_url="/xadmin/")
def op_addnews(request):
    ret = {'code':-1,'msg':"err"}
    db_id = request.POST["id"]#id
    s_id = request.POST["pf"]#服
    ser_arr=s_id.split(',')
    effect = request.POST["effect"]
    s_con = request.POST["con"]
    times = request.POST["time"]
    date_0,date_1 = request.POST["date"].split(',')
    s_date_0=date_0+':00'
    s_date_1=date_1+':00'
    isgun={'是':1,'否':0}
    #保存到数据库
    state = 1
    serial = int(time.time())
    if(db_id==''):
        ni=NewInfo()
        ni.serial = serial
    else:
        if NewInfo.objects.filter(pk=db_id).exists():
            ni=NewInfo.objects.get(pk=db_id)
            serial=ni.serial
            state=2
        else:
            ret['msg']='数据不存在'
            return HttpResponse(ujson.dumps(ret))
    ni.content=s_con
    if str(effect) !='1':
        effect=isgun[str(effect)]
    ni.effect=effect
    ni.times=times
    ni.start_time=s_date_0
    ni.end_time=s_date_1
    arr_serinfo=ServerInfo.objects.filter(pf__in=ser_arr)
    ni.save()
    for ii_server in arr_serinfo:
        ni.server.add(ii_server)
    db_id=ni.id
    if state==1:
        #提交到游戏服务器
        if cbyx_InterfaceFun.gm_broadcast_notice(ser_arr,serial,state,int(fun.TimeToStamp(s_date_0)),int(fun.TimeToStamp(s_date_1)),int(times),s_con,effect)==0:
            ret['msg']='公告发送失败'
            return HttpResponse(ujson.dumps(ret))
        else:
            ret['msg']='success'
            ni.save()
    elif state==2:
        if cbyx_InterfaceFun.gm_broadcast_notice2(ser_arr, serial, state, int(fun.TimeToStamp(s_date_0 + ' 00:00:00')),int(fun.TimeToStamp(s_date_1 + ' 00:00:00')), int(times), s_con) == 0:
            ret['msg'] = '公告修改失败'
            return HttpResponse(ujson.dumps(ret))
        else:
            ret['msg']='公告修改成功'
            ni.save()

    ret['code']=0
    return HttpResponse(ujson.dumps(ret))

#修改公告滚动状态
@csrf_exempt
@login_required(login_url="/xadmin/")
def op_change_effect(request):
    ret = {'code':-1,'msg':"err"}
    db_id = request.POST["id"]#id
    serial=request.POST['serial']
    effect=request.POST['effect']
    effect_dic={'是':1,'否':0}
    effects=''
    if db_id.isdigit():
        if NewInfo.objects.filter(pk=db_id).exists():
            ni=NewInfo.objects.get(pk=db_id)
            if effect_dic[str(effect)]==1:
                ni.effect=0
                effects=0
            else:
                ni.effect=1
                effects=1
                NewInfo.objects.filter(effect=1).update(effect=0)
            ser_arr=[]
            tmp_arr=ni.server.all()
            for ii_ser in tmp_arr:
                ser_arr.append(ii_ser.pf)
            if cbyx_InterfaceFun.gm_broadcast_notice3(ser_arr,int(serial),3,effects)==0:
                ret['msg'] = '修改滚动状态失败!'
            else:
                ret['msg']='success'
                ret['code']=0
                ni.save()
    return HttpResponse(ujson.dumps(ret))


#公告列表
@csrf_exempt
@login_required(login_url="/xadmin/")
def op_getnews(request):
    ret = []
    arr_ni=NewInfo.objects.all().order_by("-id")
    isgun={0:'否',1:'是'}
    for ii_ni in arr_ni:
        tmp_ser=''
        #print ii_ni.start_time,type(ii_ni.start_time)
        tmp_obj={'id':ii_ni.id,'effect':isgun[ii_ni.effect],'content':ii_ni.content,'start_time':ii_ni.start_time.strftime('%Y-%m-%d %H:%M:%S'),
                 'end_time':ii_ni.end_time.strftime('%Y-%m-%d %H:%M:%S '), 'time':ii_ni.times,'server':'','serial':ii_ni.serial}
        for ii_ser in ii_ni.server.all():
            if tmp_ser!='':
                tmp_ser+=','
            tmp_ser+=ii_ser.pf
        tmp_obj['server']=tmp_ser
        ret.append(tmp_obj)
    return HttpResponse(ujson.dumps(ret))





@csrf_exempt
@login_required(login_url="/xadmin/")
def op_chserver(request):
    ret = {'ret': -1, 'msg': "err"}
    serverid=request.POST['serverid']
    is_visible = request.POST['visible']
    is_new = request.POST['news']
    is_stop = request.POST['stop']
    is_hot = request.POST['hot']
    open_time = request.POST['open_time']
    if len(str(open_time).split(' ')[1].split(':'))==2:
        open_time = open_time +':00'
    if cbyx_InterfaceFun.set_server_list(int(serverid),int(is_visible),int(is_new),int(is_hot),int(is_stop),int(fun.TimeToStamp(open_time)))==0:
        ret['msg'] = '服务器修改失败'
    else:
        ret['ret']=0
        ret['msg']='success'
    return HttpResponse(ujson.dumps(ret))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_get_server(request):
    # ip_port ='123.207.24.238:9101'
    lists=[]
    ip_port = settings.ip
    url = "http://%s/query_server_list.php" % (ip_port)
    response = requests.get(url)
    result = response.json()
    is_not={0:'否',1:'是'}
    is_hot={0:'否',1:'火爆(不可进)',2:'火爆(可进)'}
    for i in result:
        ser_dic={}
        ser_dic['serverid']=i['ServerID']
        ser_dic['server_name']=i['ServerName']
        ser_dic['new']=is_not[i['IsNew']]
        ser_dic['hot']=is_hot[i['IsHot']]
        ser_dic['stop'] = is_not[i['IsStop']]
        ser_dic['is_visible'] = is_not[i['IsVisible']]
        ser_dic['open_time'] =fun.StampToTime(i['OpenUtc'])
        lists.append(ser_dic)
    return HttpResponse(ujson.dumps(lists))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_spserver(request):
    ret = {'ret': -1, 'msg': "err"}
    id=int(request.POST['id'])
    server=ServerInfo.objects.get(id=id)
    server.status=0
    server.save()
    ret['ret']=0
    ret['msg']='success'
    return HttpResponse(ujson.dumps(ret))





@csrf_exempt
@login_required(login_url="/xadmin/")
def op_login_news(request):
    ret = {'code': -1, 'msg': "err"}
    content = request.POST['content']

    if cbyx_InterfaceFun.gm_send_notice(content)==0:
        ret['msg'] = '修改登录公告失败!'
    else:
        loginnew_info = LoginNews()
        loginnew_info.content=content
        loginnew_info.save()
        ret['msg']='修改成功!'
        ret['code']=0

    return HttpResponse(ujson.dumps(ret))





@csrf_exempt
@login_required(login_url="/xadmin/")
def op_loginnew_quset(request):
    ret = {'code': -1, 'msg': "err"}
    loginnew_info = LoginNews.objects.all().order_by('-id')
    lists =[]
    for i in loginnew_info:
        ln_dic = {}
        ln_dic['ids']=i.id
        ln_dic['content'] =i.content
        ln_dic['create_time']=str(i.change_time)
        lists.append(ln_dic)

    return HttpResponse(ujson.dumps(lists))




@csrf_exempt
@login_required(login_url="/xadmin/")
def op_black(request):
    ret = {'ret': -1, 'msg': "err"}
    userid=request.POST['account']

    if cbyx_InterfaceFun.user_black(userid)==0:
        ret['msg'] = '添加黑名单失败!'
    else:
        black_info=Black_White()
        black_info.userid=userid
        black_info.operid=request.user.username
        black_info.start_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        black_info.end_time =datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        black_info.types=1
        black_info.save()

        ret['ret']=0
        ret['msg']='success'

    return HttpResponse(ujson.dumps(ret))




@csrf_exempt
@login_required(login_url="/xadmin/")
def op_bw_quset(request):
    blacks_info=Black_White.objects.filter(types=1).order_by('-id')
    lists=[]
    for i in blacks_info:
        black_dic={}
        black_dic['id']=i.id
        black_dic['userid']=i.userid
        black_dic['operid']=i.operid
        black_dic['create_time']=str(i.create_time)
        lists.append(black_dic)
    return HttpResponse(ujson.dumps(lists))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_bw_delete(request):
    ret = {'ret': -1, 'msg': "err"}
    userid = request.POST['userid']
    id = int(request.POST['id'])

    if cbyx_InterfaceFun.user_black(userid)==0:
        ret['msg'] = '恢复黑名单失败!'
    else:
        try:
            with transaction.commit_on_success():
                Black_White.objects.get(id=id).delete()
                ret['msg']='success'
        except:
            ret['msg'] = '发送服务器(恢复黑名单)成功,删除记录失败!'
            ret['ret'] = -1
            return HttpResponse(ujson.dumps(ret))

    ret['ret'] = 0
    return HttpResponse(ujson.dumps(ret))


@csrf_exempt
@login_required(login_url="/xadmin/")
def op_white(request):
    ret = {'ret': -1, 'msg': "err"}
    userid = request.POST['account']

    if cbyx_InterfaceFun.usergm(userid,1)==0:
        ret['msg'] = '添加白名单失败!'
    else:
        white_info = Black_White()
        white_info.userid=userid
        white_info.f_gm=1
        white_info.operid = request.user.username
        white_info.start_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        white_info.end_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        white_info.types=0
        white_info.save()

        ret['ret'] = 0
        ret['msg'] = 'success'
    return HttpResponse(ujson.dumps(ret))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_wh_quset(request):
    blacks_info=Black_White.objects.filter(types=0).order_by('-id')
    lists=[]
    for i in blacks_info:
        black_dic={}
        black_dic['id']=i.id
        black_dic['userid']=i.userid
        black_dic['operid']=i.operid
        black_dic['create_time']=str(i.create_time)
        lists.append(black_dic)
    return HttpResponse(ujson.dumps(lists))



@csrf_exempt
@login_required(login_url="/xadmin/")
def op_wh_delete(request):
    ret = {'ret': -1, 'msg': "err"}
    userid = request.POST['userid']
    id = int(request.POST['id'])

    if cbyx_InterfaceFun.usergm(userid,0) == 0:
        ret['msg'] = '删除白名单失败!'
    else:
        try:
            with transaction.commit_on_success():
                Black_White.objects.get(id=id).delete()
                ret['msg']='success'
        except:
            ret['msg'] = '发送服务器(删除白名单)成功,删除记录失败!'
            ret['ret'] = -1
            return HttpResponse(ujson.dumps(ret))

    ret['ret'] = 0
    return HttpResponse(ujson.dumps(ret))
